<template>
  <n-button size="tiny" ghost class="px-10px mr-10px" @click="handleExport">
    <icon-uil:file-export class="mr-5px" />导出
  </n-button>
</template>

<script setup lang="ts">
import * as XLSX from 'xlsx';
import { useDateFormat } from '@vueuse/core';
import { fetchPurchaseSettlementDetails } from '@/service';
import { useBillContext } from '@/context';

const { useInject } = useBillContext();
const { billNo } = useInject();

/*
 * @description:
 * @param {Object} json 服务端发过来的数据
 * @param {Object} head 导出Excel表头
 * @param {String} name 导出文件名
 * @return:
 */
async function exportExcel(json: any, head: any, name: string) {
  const list = json.map((item: any) => {
    const obj: any = {};
    for (const k in item) {
      if (head[k]) {
        obj[head[k]] = item[k];
      }
    }
    return obj;
  });

  // 创建工作表
  const data = XLSX.utils.json_to_sheet(list);
  // 创建工作簿
  const wb = XLSX.utils.book_new();
  // 将工作表放入工作簿中
  XLSX.utils.book_append_sheet(wb, data, name);
  // 生成文件并下载
  const time = useDateFormat(new Date(), 'YYYYMMDDhhmmss').value;
  await XLSX.writeFile(wb, `${name}_${time}.xlsx`);
}

async function handleExport() {
  const res: any = await fetchPurchaseSettlementDetails(billNo.value);
  if (res.data) {
    const excelHead = {
      A_BILLDATE: '日期',
      A_BILLTYPE: '单别',
      A_BILLNO: '单据编号',
      A_ORGBILLNO: '报检单号',
      A_ITEMID_ITEMCODE: '商品编号',
      A_ITEMID_ITEMNAME: '商品名称',
      A_ITEMID_ITEMDESC: '规格描述',
      A_ITEMID_MODEL: '商品型号',
      A_ITEMPECULIARITY_ATTRIBUTE1ID_DESCRIPTION: '颜色',
      A_ITEMPECULIARITY_ATTRIBUTE4ID_DESCRIPTION: '仓位',
      A_ITEMPECULIARITY_ATTRIBUTE2ID_DESCRIPTION: '旧物料编码',
      A_ITEMPECULIARITY_ATTRIBUTE3ID_DESCRIPTION: '供应商',
      A_UNITTYPE: '单位',
      A_QTY: '数量',
      A_DEALTYPE: '处理方式',
      A_UNITCOST: '标准成本价',
      A_ISBASE: '正式价格',
      A_PRICE: '入库价格',
      A_JSPRICE: '结算价格',
      A_COST: '标准成本金额',
      A_AMOUNT: '入库金额',
      A_JSAMOUNT: '结算金额',
      A_JSAGIO1: '损耗折扣价',
      A_JSAGIO1AMT: '损耗折扣额',
      A_JSAGIO2: '促销折扣价',
      A_JSAGIO2AMT: '促销折扣额',
      A_JSAGIO3: '调整折扣价',
      A_JSAGIO3AMT: '调整折扣额',
      A_JSAGIO: '结算总折扣价',
      A_JSRPRICE: '结算扣款后价格',
      A_JSRAMOUNT: '结算扣款后金额',
      A_CYPRICE: '价格差异',
      A_CYAMOUNT: '差异金额',
      A_JSTIME: '结算时间',
      A_OREMARK: '备注',
      A_WHID_WHNAME: '仓库名称',
      A_DEPTID_DEPTNAME: '部门名称',
      A_JSRTAXAMT: '结算扣款后税额'
    };
    exportExcel(res.data, excelHead, '结算明细');
    window.$message?.success(`导出成功`);
  } else {
    window.$message?.error(`导出失败`);
  }
}
</script>

<style scoped></style>
